package com.site.blog.my.core.exception;

import com.site.blog.my.core.util.Result;
import com.site.blog.my.core.util.ResultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author xuwangcheng
 * @version 1.0.0
 * @description
 * @date 2020/4/28 17:20
 */
@RestControllerAdvice
public class AppExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(AppExceptionHandler.class);

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(AppException.class)
    public Result handleRenException(AppException ex){
        LOGGER.error(ex.getMsg());
        Result result = ResultGenerator.genErrorResult(ex.getCode(), ex.getMsg());

        return result;
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException ex){
        LOGGER.error(ex.getMessage(), ex);
        Result result = ResultGenerator.genErrorResult(AppErrorCode.DATABASE_EXCEPTION);

        return result;
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception ex){
        LOGGER.error(ex.getMessage(), ex);

        return ResultGenerator.genErrorResult(AppErrorCode.SERVER_ERROR);
    }
}
